package it.univpm.diiga.memorysim.views;
 
import it.univpm.diiga.memorysim.data.DataPlugin;
import org.eclipse.swt.custom.TableEditor;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.layout.GridData;

public class SequenceSimulationSeg extends ViewPart {

	public static final String ID = "it.univpm.diiga.memorysim.views.SequenceSimulationSeg"; // TODO Needs to be whatever is mentioned in plugin.xml
	private Composite top = null;
	private Label labelListEvent = null;
	private Table tableEvent = null;
	@SuppressWarnings("unused")
	private TableViewer tableViewer = null;
	private Button eventToSeq,eventToSeq1 = null;
	private Button delButton = null;
	private Table tableSeqSimulation = null;
	@SuppressWarnings("unused")
	private TableViewer tableViewer1 = null;
	private Label labelOperazioni = null;
	@Override
	public void createPartControl(Composite parent) {
		// TODO Auto-generated method stub

		GridData gridData1 = new GridData();
		gridData1.verticalSpan = 7;
		gridData1.verticalAlignment = GridData.CENTER;
		gridData1.horizontalIndent = 0;
		gridData1.heightHint = 216;
		gridData1.widthHint = 400;
		gridData1.horizontalAlignment = GridData.FILL;
		GridData gridData = new GridData();
		gridData.verticalSpan = 7;
		gridData.verticalAlignment = GridData.FILL;
		gridData.widthHint = 400;
		gridData.heightHint = 216;
		gridData.horizontalAlignment = GridData.FILL;
		GridLayout gridLayout = new GridLayout();
		gridLayout.numColumns = 3;
		gridLayout.verticalSpacing = 5;
		gridLayout.horizontalSpacing = 5;
		top = new Composite(parent, SWT.NONE);
		top.setLayout(gridLayout);
		labelListEvent = new Label(top, SWT.NONE);
		labelListEvent.setText("Lista degli eventi");
		@SuppressWarnings("unused")
		Label filler3 = new Label(top, SWT.NONE);
		labelOperazioni = new Label(top, SWT.NONE);
		labelOperazioni.setText("Operazioni");
		tableEvent = new Table(top, SWT.NONE|SWT.BORDER);
		tableEvent.setHeaderVisible(true);
		tableEvent.setLayoutData(gridData1);
		tableEvent.setLinesVisible(true);
		TableColumn column1 = new TableColumn (tableEvent, SWT.CENTER);
		TableColumn column2 = new TableColumn (tableEvent, SWT.CENTER);
		column2.setText ("Segmento");
		TableColumn column3 = new TableColumn (tableEvent, SWT.CENTER);
		column3.setText ("Dimensione [Kb]");
		column3.setWidth(130);
		column1.setText ("Processo");
		final TableEditor editor = new TableEditor(tableEvent);
	    editor.horizontalAlignment = SWT.LEFT;
	    editor.grabHorizontal = true;
	    editor.minimumWidth = 50;
		column1.setWidth(130);
		column2.setWidth(130);
		@SuppressWarnings("unused")
		Label filler7 = new Label(top, SWT.NONE);
		tableSeqSimulation = new Table(top, SWT.NONE|SWT.BORDER);
		tableSeqSimulation.setHeaderVisible(true);
		tableSeqSimulation.setLayoutData(gridData);
		tableSeqSimulation.setLinesVisible(true);
		TableColumn col1Proc = new TableColumn (tableSeqSimulation, SWT.CENTER);
		TableColumn col2Pag = new TableColumn (tableSeqSimulation, SWT.CENTER);
		TableColumn col3Type = new TableColumn (tableSeqSimulation, SWT.CENTER);
		col1Proc.setText ("Processo");
		 col2Pag.setText ("Segmento");
		 col3Type.setText ("Tipo");
		col2Pag.setWidth(185);
		col1Proc.setWidth(185);
		col3Type.setWidth(30);
		tableViewer1 = new TableViewer(tableSeqSimulation);
		@SuppressWarnings("unused")
		Label filler4 = new Label(top, SWT.NONE);
		@SuppressWarnings("unused")
		Label filler12 = new Label(top, SWT.NONE);
		eventToSeq = new Button(top, SWT.NONE);
		eventToSeq.setText("r ->");
		eventToSeq1 = new Button(top, SWT.NONE);
		eventToSeq1.setText("w ->");
		@SuppressWarnings("unused")
		Label filler75 = new Label(top, SWT.NONE);
		@SuppressWarnings("unused")
		Label filler8 = new Label(top, SWT.NONE);
		@SuppressWarnings("unused")
		Label filler711 = new Label(top, SWT.NONE);
		@SuppressWarnings("unused")
		Label filler715 = new Label(top, SWT.NONE);
		@SuppressWarnings("unused")
		Label filler716 = new Label(top, SWT.NONE);
		delButton = new Button(top, SWT.NONE);
		delButton.setText("Elimina Operazione");
		tableViewer = new TableViewer(tableEvent);		
		tableEvent.addSelectionListener(new SelectionAdapter() {
			      public void widgetSelected(SelectionEvent e) {
				        // Clean up any previous editor control
				        Control oldEditor = editor.getEditor();
				        if (oldEditor != null)
				          oldEditor.dispose();

				        // Identify the selected row
				        TableItem item = (TableItem) e.item;
				        if (item == null)
				          return;

				        // The control that will be the editor must be a child of the
				        // Table
				        Text newEditor = new Text(tableEvent, SWT.NONE);
				        newEditor.setText(item.getText(2));
				        newEditor.addModifyListener(new ModifyListener() {
				          public void modifyText(ModifyEvent me) {
				            Text text = (Text) editor.getEditor();
				            editor.getItem()
				                .setText(2, text.getText());
				          }
				        });
				        newEditor.selectAll();
				        newEditor.setFocus();
				        editor.setEditor(newEditor, item, 2);
				      }
				    });
		Button but = new Button(top, SWT.NONE);
		but.setText("Applica");
		but.addSelectionListener(new SelectionListener(){

			public void widgetDefaultSelected(SelectionEvent e) {	}

			public void widgetSelected(SelectionEvent e) {
				updateList();
				openView();
			}
			
		});
	
		tableSeqSimulation.addMouseListener(new MouseListener(){

			public void mouseDoubleClick(MouseEvent e) {
				TableItem[] itemEvent=tableEvent.getSelection();
				if(itemEvent.length>0){
				TableItem item1 = new TableItem (tableSeqSimulation, SWT.NONE);
				
				item1.setText (0,itemEvent[0].getText(0));
				item1.setText (1,itemEvent[0].getText(1));
				item1.setText (2,"r");
				}
			}

			public void mouseDown(MouseEvent e) {}

			public void mouseUp(MouseEvent e) {}
			
		});
		eventToSeq1.addSelectionListener(new SelectionListener(){

			@Override
			public void widgetDefaultSelected(SelectionEvent e) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void widgetSelected(SelectionEvent e) {
				TableItem[] itemEvent=tableEvent.getSelection();
				if(itemEvent.length>0){
				TableItem item1 = new TableItem (tableSeqSimulation, SWT.NONE);
				
				item1.setText (0,itemEvent[0].getText(0));
				item1.setText (1,itemEvent[0].getText(1));
				item1.setText (2,"w");
				}
			}
			
		});
		eventToSeq.addSelectionListener(new SelectionListener(){

			@Override
			public void widgetDefaultSelected(SelectionEvent e) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void widgetSelected(SelectionEvent e) {
				TableItem[] itemEvent=tableEvent.getSelection();
				if(itemEvent.length>0){
				TableItem item1 = new TableItem (tableSeqSimulation, SWT.NONE);
				
				item1.setText (0,itemEvent[0].getText(0));
				item1.setText (1,itemEvent[0].getText(1));
				item1.setText (2,"r");
				}
			}
			
		});
		delButton.addSelectionListener(new SelectionListener(){
			public void widgetDefaultSelected(SelectionEvent e) {	}
			
			public void widgetSelected(SelectionEvent e) {
				tableSeqSimulation.remove(tableSeqSimulation.getSelectionIndices());
			}
		});
		popolateSegment();
		Load();
	}

	private void Load() {
		if(DataPlugin.listProcessRequest!=null){
				for(int i=0;i<DataPlugin.listProcessRequest.size();i++){
					TableItem item1 = new TableItem (tableSeqSimulation, SWT.NONE);		
					item1.setText (0,DataPlugin.listProcessRequest.get(i).getPID()+"");
					item1.setText (1,DataPlugin.listProcessRequest.get(i).getSegmento()+"");
					item1.setText (2,DataPlugin.listProcessRequest.get(i).getType()+"");
				}
			}
	}

	public void popolateSegment(){
		for(int i=0;i<DataPlugin.listSegmentP.size();i++){
			int n=DataPlugin.listSegmentP.get(i);
			for (int j=0;j<n;j++){
				TableItem item1 = new TableItem (tableEvent, SWT.NONE);
				item1.setText (0,i+1+"");
				item1.setText (1, j+1+"");
				item1.setText (2, DataPlugin.findProcessRequestDim(i+1, j+1)+"");
			}
		}
	}
	@Override
	public void setFocus() {

	}

	private void updateList(){
		DataPlugin.newProcessList();
		DataPlugin.ramUsed=0;
		int pid=1;
		int dim=0;
		for(int i=0;i<tableEvent.getItemCount();i++){
			try{
			int pid1=Integer.parseInt(tableEvent.getItem(i).getText(0));
			if(pid==pid1){
				dim+=Integer.parseInt(tableEvent.getItem(i).getText(2));		
			}else{
				DataPlugin.addProcess(pid,dim);
				DataPlugin.ramUsed+=dim;
				dim=0;
				dim+=Integer.parseInt(tableEvent.getItem(i).getText(2));
				
			}
			if(tableEvent.getItemCount()-1==i){
				if(pid==pid1){
					dim+=Integer.parseInt(tableEvent.getItem(i).getText(2));
					DataPlugin.addProcess(pid,dim);
					DataPlugin.ramUsed+=dim;
				}else{
					
					dim=Integer.parseInt(tableEvent.getItem(i).getText(2));
					DataPlugin.addProcess(pid1,dim);
					DataPlugin.ramUsed+=dim;
				}
			}
			pid=pid1;
			}catch(Exception noNum){
				MessageDialog.openError(null, "Error", "Dati inseriti errati:" + noNum.getMessage());
				break;
			}
		}
		DataPlugin.newProcessRequest();
		for(int i=0;i<tableSeqSimulation.getItemCount();i++){
			TableItem itemEvent = tableSeqSimulation.getItem(i);
			int proc=Integer.parseInt(itemEvent.getText(0));
			int seg=Integer.parseInt(itemEvent.getText(1));
			String type=itemEvent.getText(2);
			int dim1=1;
			for(int j=0;j<tableEvent.getItemCount();j++){
				int pid1=Integer.parseInt(tableEvent.getItem(j).getText(0));
				int seg1=Integer.parseInt(tableEvent.getItem(j).getText(1));
				if(proc==pid1 && seg==seg1) dim1=Integer.parseInt(tableEvent.getItem(j).getText(2));
			}
			DataPlugin.addProcessRequest(proc, seg,type,dim1);
		}
	}
	
	private void openView(){
		IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
		try {
			 window.getActivePage().showView(MemoryCentralInitialSituationDinamic.ID, "Inital mem", IWorkbenchPage.VIEW_ACTIVATE);
		} catch (PartInitException e1) {
			MessageDialog.openError(window.getShell(), "Error", "Error opening view:" + e1.getMessage());
		}
	}
	
} 
